import { create } from "zustand";
import { TIconName } from "../components/SvgIcon";
import {
  fetchDeleteMessage,
  fetchGetChatInfo,
  fetchUpdateChat,
  getPlatformId,
} from "@/api/server/recommend_question";
import markdownStr from "@/mock/markdown-txt";
import markdownIt from "markdown-it";
import { randomNumber } from "@/utils";
import dayjs from "dayjs";

export interface ILegalAdviceItem {
  key: string;
  name: string;
  is_favorite?: boolean;
  icon?: TIconName;
  time: string;
}

export interface IChatItem {
  key: string;
  text: string;
  size?: string;
  message?: string;
  sender?: string;
  chatId?: string;
  answerType?: string;
  type?: string;
  loading?: boolean;
  like?: boolean;
  dislike?: boolean;
  stop?: boolean;
  isMarkdown?: boolean;
}

export interface ILegalAdviceStoreState {
  list: ILegalAdviceItem[];
  chatList?: IChatItem[];
  activeKey: string;
  tabType?: string;
  listType?: string;
  listSearch?: string;
  formValues?: any;
  collapse: boolean;
  setListSearch?: (k: string) => void;
  setListType?: (k: string) => void;
  deleteChatAndReAnswer?: (item: any) => void;
  setActiveKey: (k: string, message?: string) => Promise<void>;
  setCollapse: (k: boolean) => void;
  appendChatList?: (message: any) => void;
  updateChatList?: (k: string, message: any) => void;
  setTabType?: (k: string) => void;
  setFormValues?: (formValues: any) => void;
  onSendMessage?: (message: string, chatId: string) => Promise<void>;
  onStopAnswering?: (message: string) => Promise<void>;
  updateLoadingChat?: (message: string, answerType?: string) => Promise<void>;
  refreshList?: () => Promise<void>;
  clear: () => void;
}

interface IAppState {
  logined: boolean;
  isYongGongXia: boolean;
  setLogined: (b: boolean) => void;
}

export const useAppStore = create<IAppState>((set, get) => {
  return {
    // 是否已经登录
    logined: true,
    // 是否用功侠跳转过来的
    isYongGongXia: getPlatformId() === "BaihuaYongGongXia",
    setLogined(b) {
      set({ logined: b });
    },
  };
});

export const useLegalAdviceStore = create<ILegalAdviceStoreState>(
  (set, get) => {
    return {
      list: [
        {
          key: "1",
          name: "rust 使用 imageproc 实现判断一个图片内是否包含另外一个图片",
          time: "2024-12-01 09:39:35",
        },
      ],
      // 聊天内容
      chatList: [
        {
          key: "1",
          text: "rust 实现 图片识别",
        },
        {
          key: "2",
          isMarkdown: true,
          text: markdownStr,
        },
        {
          key: "3",
          text: "朋友借了我10万块钱，约定两个月归还且不需要利息。已经半年过去了但他一直没有还，我可以要求增加利息吗？",
        },
      ],
      activeKey: "",
      listType: "history",
      setListType: (k: string) => {
        set({ listType: k });
        get().refreshList();
      },
      listSearch: "",
      setListSearch: (k: string) => {
        set({ listSearch: k });
        get().refreshList();
      },
      collapse: false,
      clear: () => {
        set(() => ({ activeKey: "", chatList: [], list: [] }));
      },
      updateLoadingChat: async (message: string, answerType?: string) => {
        const chatId = get().activeKey;
        const chatList = get().chatList;
        const res = await fetchUpdateChat({
          chat_id: chatId,
          message,
        });

        const md = new markdownIt();

        chatList.pop();

        chatList.push({
          key: res.data.child_chat_id,
          message: message,
          chatId: chatId,
          answerType,
          isMarkdown: true,
          text: md.render(message.replace(/([^\n])\n([^\n])/g, "$1\n\n$2")),
        });

        set(() => ({ chatList: [...chatList] }));
      },
      onSendMessage: async (message: string, chatId: string) => {
        await fetchUpdateChat({
          chat_id: chatId,
          sender: "user",
          message,
        });

        set((state) => {
          const chatList = [...state.chatList];

          chatList.push({
            key: randomNumber(),
            text: message,
          });

          chatList.push({
            key: randomNumber(),
            message: message,
            chatId: chatId,
            loading: true,
            isMarkdown: true,
            text: "",
          });

          return { chatList };
        });
      },
      onStopAnswering: async (message: string) => {
        const chatList = get().chatList;
        const index = chatList?.findIndex((item) => item.loading);

        if (index >= 0) {
          chatList[index].stop = true;
          chatList[index].loading = false;
          chatList[index].text = message;
        }

        set({ chatList: [...chatList] });
      },
      deleteChatAndReAnswer: async (item: any) => {
        const chatList = get().chatList;
        const chatId = get().activeKey;
        chatList.pop();
        const last = chatList[chatList.length - 1];
        await fetchDeleteMessage(item.key);

        chatList.push({
          key: randomNumber(),
          message: last.message,
          chatId: chatId,
          loading: true,
          isMarkdown: true,
          text: "",
        });

        set(() => ({ chatList: [...chatList] }));
      },
      setActiveKey: async (k: string, message?: string) => {
        if (!k) {
          set(() => ({ activeKey: k, chatList: [] }));
          return;
        }
        const res = await fetchGetChatInfo({
          search_type: "chat_id",
          chat_id: k,
          type: "QA",
        });
        const md = new markdownIt();
        let hasLawyerAnswer = false;
        const chatList =
          res?.data?.chat_info?.messages?.map((item) => {
            const isMarkdown = item.sender === "robot";
            if (!hasLawyerAnswer && item.sender === "lawyer") {
              hasLawyerAnswer = true;
            }
            return {
              key: item.child_chat_id,
              like: item.like,
              dislike: item.dislike,
              isMarkdown,
              type: item.type,
              size: item.size,
              status: item.status,
              message: item.message,
              sender: item.sender,
              text: isMarkdown
                ? md.render(
                    item.message.replace(/([^\n])\n([^\n])/g, "$1\n\n$2")
                  )
                : item.message,
            };
          }) || [];
        const lastChatList = chatList?.[chatList.length - 1];
        const lastIsQuestion = lastChatList?.text && !lastChatList?.isMarkdown;

        if (!message && lastIsQuestion && !hasLawyerAnswer) {
          // 如果最后一个是 用户问题，则继续生成对话
          message = lastChatList.text;
        }

        if (message) {
          chatList.push({
            key: randomNumber(),
            message: message,
            chatId: k,
            loading: true,
            isMarkdown: true,
            text: "",
          });
        }
        set(() => ({ activeKey: k, chatList }));
      },
      setCollapse: (k: boolean) => set(() => ({ collapse: k })),
      appendChatList: (message: any) => {
        const chatId = get().activeKey;
        return set((state) => {
          if (typeof message === "string") {
            return {
              chatList: state.chatList?.concat([
                { key: randomNumber(), text: message },
              ]),
            };
          }

          if (chatId === message?.chat_id) {
            return {
              chatList: state.chatList?.concat([message]),
            };
          }

          return {
            chatList: state.chatList,
          };
        });
      },
      updateChatList: (key: string, message: any) => {
        set((state) => {
          const index = state.chatList?.findIndex((item) => item.key === key);

          if (index >= 0) {
            state.chatList[index] = { ...state.chatList[index], ...message };
          }

          return {
            chatList: [...state.chatList],
          };
        });
      },
      // 刷新列表
      refreshList: async () => {
        const listSearch = get().listSearch;
        const listType = get().listType;
        const res = await fetchGetChatInfo({
          search_type: "user_id",
          type: "QA",
          query: listSearch,
          is_favorite: listType === "favorites" ? true : undefined,
        });
        const list = res?.data?.chat_info?.data
          ?.filter((item) => !item.is_deleted)
          ?.map((item) => {
            return {
              key: item.chat_id,
              is_favorite: item.is_favorite,
              is_pinned: item.is_pinned,
              name: item.title,
              time: dayjs(item.updated_at).format("YYYY-MM-DD HH:mm:ss"),
            };
          });
        set(() => ({ list }));
      },
    };
  }
);

export const useDocGenerationStore = create<ILegalAdviceStoreState>(
  (set, get) => {
    return {
      list: [
        {
          key: "1",
          name: "rust 使用 imageproc 实现判断一个图片内是否包含另外一个图片",
          time: "2024-12-01 09:39:35",
        },
      ],
      activeKey: "",
      collapse: false,
      listType: "history",
      setListType: (k: string) => {
        set({ listType: k });
        get().refreshList();
      },
      listSearch: "",
      setListSearch: (k: string) => {
        set({ listSearch: k });
        get().refreshList();
      },
      clear: () => {
        set(() => ({ activeKey: "", list: [] }));
      },
      setActiveKey: async (k: string) => {
        set(() => ({ activeKey: k }));
      },
      setCollapse: (k: boolean) => set(() => ({ collapse: k })),
      // 刷新列表
      refreshList: async () => {
        const listSearch = get().listSearch;
        const listType = get().listType;
        const res = await fetchGetChatInfo({
          search_type: "user_id",
          type: "wenshu",
          query: listSearch,
          is_favorite: listType === "favorites" ? true : undefined,
        });
        const list = res?.data?.chat_info?.data
          ?.filter((item) => !item.is_deleted)
          ?.map((item) => {
            return {
              key: item.chat_id,
              is_favorite: item.is_favorite,
              is_pinned: item.is_pinned,
              name: item.title,
              time: dayjs(item.updated_at).format("YYYY-MM-DD HH:mm:ss"),
            };
          });
        set(() => ({ list }));
      },
    };
  }
);

export const useLegalSearchStore = create<ILegalAdviceStoreState>(
  (set, get) => {
    return {
      list: [
        {
          key: "1",
          name: "rust 使用 imageproc 实现判断一个图片内是否包含另外一个图片",
          time: "类案检索 ｜ 2024-12-01 09:39:35",
          icon: "icon-leianjiansuo",
        },
      ],
      chatList: [],
      tabType: "1",
      activeKey: "",
      collapse: true,
      formValues: {},
      listType: "history",
      setListType: (k: string) => {
        set({ listType: k });
        get().refreshList();
      },
      listSearch: "",
      setListSearch: (k: string) => {
        set({ listSearch: k });
        get().refreshList();
      },
      clear: () => {
        set(() => ({
          activeKey: "",
          chatList: [],
          list: [],
          formValues: {},
          collapse: true,
        }));
      },
      setTabType: (k: string) => set(() => ({ tabType: k })),
      setFormValues: (formValues: any) => set(() => ({ formValues })),
      setActiveKey: async (k: string) => {
        if (!k) {
          set(() => ({ activeKey: k, chatList: [] }));
          return;
        }
        const res = await fetchGetChatInfo({
          search_type: "chat_id",
          chat_id: k,
          type: "Law",
        });
        const md = new markdownIt();
        const chatList = res?.data?.chat_info?.messages?.map((item) => {
          const isMarkdown = item.sender === "robot";
          return {
            key: item.timestamp,
            isMarkdown,
            text: isMarkdown ? md.render(item.message) : item.message,
          };
        });
        set(() => ({ activeKey: k, chatList }));
      },
      updateLoadingChat: async (message: string) => {
        const chatId = get().activeKey;
        const chatList = get().chatList;
        const setActiveKey = get().setActiveKey;
        const res = await fetchUpdateChat({
          chat_id: chatId,
          message,
        });
        setActiveKey(chatId);
      },
      setCollapse: (k: boolean) => set(() => ({ collapse: k })),
      // 刷新列表
      refreshList: async () => {
        const listSearch = get().listSearch;
        const listType = get().listType;
        const res = await fetchGetChatInfo({
          search_type: "user_id",
          type: "Law",
          query: listSearch,
          is_favorite: listType === "favorites" ? true : undefined,
        });
        const list = res?.data?.chat_info?.data
          ?.filter((item) => !item.is_deleted)
          ?.map((item) => {
            return {
              key: item.chat_id,
              is_favorite: item.is_favorite,
              is_pinned: item.is_pinned,
              name: item.title,
              icon: "icon-leianjiansuo",
              time: dayjs(item.updated_at).format("YYYY-MM-DD HH:mm:ss"),
            };
          });
        set(() => ({ list }));
      },
    };
  }
);

export const useTextReadStore = create<ILegalAdviceStoreState>((set, get) => {
  return {
    list: [],
    chatList: [],
    tabType: "1",
    activeKey: "",
    collapse: false,
    formValues: {},
    listType: "history",
    setListType: (k: string) => {
      set({ listType: k });
      get().refreshList();
    },
    listSearch: "",
    setListSearch: (k: string) => {
      set({ listSearch: k });
      get().refreshList();
    },
    clear: () => {
      set(() => ({
        activeKey: "",
        chatList: [],
        list: [],
        formValues: {},
        collapse: true,
      }));
    },
    setTabType: (k: string) => set(() => ({ tabType: k })),
    setFormValues: (formValues: any) => set(() => ({ formValues })),
    setActiveKey: async (k: string) => {
      if (!k) {
        set(() => ({ activeKey: k, chatList: [] }));
        return;
      }
      const res = await fetchGetChatInfo({
        search_type: "chat_id",
        chat_id: k,
        type: "Law",
      });
      const md = new markdownIt();
      const chatList = res?.data?.chat_info?.messages?.map((item) => {
        const isMarkdown = item.sender === "robot";
        return {
          key: item.timestamp,
          isMarkdown,
          text: isMarkdown ? md.render(item.message) : item.message,
        };
      });
      set(() => ({ activeKey: k, chatList }));
    },
    updateLoadingChat: async (message: string) => {
      const chatId = get().activeKey;
      const chatList = get().chatList;
      const setActiveKey = get().setActiveKey;
      const res = await fetchUpdateChat({
        chat_id: chatId,
        message,
      });
      setActiveKey(chatId);
    },
    setCollapse: (k: boolean) => set(() => ({ collapse: k })),
    // 刷新列表
    refreshList: async () => {
      const res = await fetchGetChatInfo({
        search_type: "user_id",
        type: "Law",
      });
      const list = res?.data?.chat_info
        ?.filter((item) => !item.is_deleted)
        ?.map((item) => {
          return {
            key: item.chat_id,
            is_favorite: item.is_favorite,
            is_pinned: item.is_pinned,
            name: item.title,
            icon: "icon-leianjiansuo",
            time: dayjs(item.updated_at).format("YYYY-MM-DD HH:mm:ss"),
          };
        });
      set(() => ({ list }));
    },
  };
});
